package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"strconv"
	"video-api/internal/consts"
	"video-api/internal/dao"
	"video-api/utility/queue"
	"video-api/utility/redis_client"

	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/hibiken/asynq"
)

type DelDramaHistoryHandler struct{}

func NewDelDramaHistoryHandler() *DelDramaHistoryHandler {
	return &DelDramaHistoryHandler{}
}

func (d *DelDramaHistoryHandler) ProcessTask(ctx context.Context, task *asynq.Task) error {
	fmt.Println("Processing DelDramaHistory task================================")
	var data queue.DelShortDramaHistory
	err := json.Unmarshal(task.Payload(), &data)
	if err != nil {
		g.Log().Error(ctx, "json unmarshal err:", err)
		return err
	}
	err = g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
		sdrModel := dao.ShortDramaRecord.Ctx(ctx)
		res, err := sdrModel.Where("id = ?", data.RecordId).
			Fields("id,short_drama_id,episodes_id,play_at,short_name,description,cover_img,tags,order").One()
		if err != nil {
			g.Log().Error(ctx, "del drama history:query record error:", err)
			return fmt.Errorf("query record error: %w", err)
		}
		if len(res) == 0 {
			g.Log().Error(ctx, "del drama history:record not exist:", data.RecordId)
			return fmt.Errorf("record not exist: %d", data.RecordId)
		}
		// 软删除mysql
		result, err := sdrModel.Where("id = ?", data.RecordId).Delete()
		if err != nil {
			g.Log().Error(ctx, "del drama history:delete record error:", err)
			return fmt.Errorf("delete record error: %w", err)
		}
		affected, err := result.RowsAffected()
		if err != nil {
			g.Log().Error(ctx, "del drama history:get affected rows error:", err)
			return fmt.Errorf("get affected rows error: %w", err)
		}
		if affected == 0 {
			g.Log().Error(ctx, "del drama history:delete failed, no rows affected:", data.RecordId)
			return fmt.Errorf("delete failed, no rows affected")
		}
		// 删除 Redis 缓存
		if err = deleteRedisHistory(ctx, data.UserId, res); err != nil {
			g.Log().Error(ctx, "del drama history:delete redis history error:", err)
			return fmt.Errorf("delete redis history error: %w", err)
		}
		return nil
	})
	if err != nil {
		g.Log().Error(ctx, "del drama history:delHistoryRecord transaction failed:", err)
		return err
	}
	return nil
}

func deleteRedisHistory(ctx context.Context, userId int64, record gdb.Record) error {
	historyData := g.Map{
		"id":           record["id"],
		"shortDramaId": record["short_drama_id"],
		"shortName":    record["short_name"],
		"description":  record["description"],
		"coverImg":     record["cover_img"],
		"tags":         record["tags"],
		"order":        record["order"],
		"episodesId":   record["episodes_id"],
	}
	m, err := json.Marshal(historyData)
	if err != nil {
		g.Log().Error(ctx, "del drama history:marshal history data error:", err)
		return fmt.Errorf("marshal history data error: %w", err)
	}
	key := consts.SHORT_DRAMA_HISTORY + ":" + strconv.Itoa(int(userId))
	if err = redis_client.RedisClient.ZRem(ctx, key, m).Err(); err != nil {
		g.Log().Error(ctx, "del drama history:remove from redis error:", err)
		return fmt.Errorf("remove from redis error: %w", err)
	}
	return nil
}
